<template>
  <div>
    <qrcode-stream :key="_uid" :track="this.paintOutline" @decode="handleDecode" @init="initScanner" style="height: 100vh; width: 100vw;">
      <a-icon @click="handleClose" style="position: absolute; top: 50px; right: 50px; color: white; font-size: 32px;" type="close"/>
    </qrcode-stream>
  </div>
</template>

<script>
import {QrcodeStream} from 'vue-qrcode-reader'
export default {
  components: {
    QrcodeStream
  },
  name: "index",
  methods: {
    paintOutline (detectedCodes, ctx) {
      for (const detectedCode of detectedCodes) {
        const [ firstPoint, ...otherPoints ] = detectedCode.cornerPoints

        ctx.strokeStyle = "red";

        ctx.beginPath();
        ctx.moveTo(firstPoint.x, firstPoint.y);
        for (const { x, y } of otherPoints) {
          ctx.lineTo(x, y);
        }
        ctx.lineTo(firstPoint.x, firstPoint.y);
        ctx.closePath();
        ctx.stroke();
      }
    },
    handleDecode (content) {
      this.$emit('handleDecode', content)
    },
    handleClose () {
      this.$emit('handleClose')
    },
    async initScanner (promise) {
      // this.$message.info('open')
      // promise.catch(console.error)
      try {
        await promise
      } catch (error) {
        if (error.name === 'NotAllowedError') {
          this.error = "ERROR: you need to grant camera access permission"
        } else if (error.name === 'NotFoundError') {
          this.error = "ERROR: no camera on this device"
        } else if (error.name === 'NotSupportedError') {
          this.error = "ERROR: secure context required (HTTPS, localhost)"
        } else if (error.name === 'NotReadableError') {
          this.error = "ERROR: is the camera already in use?"
        } else if (error.name === 'OverconstrainedError') {
          this.error = "ERROR: installed cameras are not suitable"
        } else if (error.name === 'StreamApiNotSupportedError') {
          this.error = "ERROR: Stream API is not supported in this browser"
        } else if (error.name === 'InsecureContextError') {
          this.error = 'ERROR: Camera access is only permitted in secure context. Use HTTPS or localhost rather than HTTP.';
        } else {
          this.error = `ERROR: Camera error (${error.name})`;
        }
        this.$message.error(this.error)
      }
    }
  }
}
</script>

<style scoped>

</style>